--settings
local priority = 4

--local cache


EntitySystem.updatesystem("physics", priority, function(dt) 
     
  for e in pairs(EntitySystem.query("physical")) do
    if not e.physics.body then
      --create a new physics entity
      --Added a 1px bumper to the shapes. Usually makes the graphics look a little bit better on collisions
      e.physics.body = love.physics.newBody(world, e.position.x+1, e.position.y+1, e.physics.bodyType)
      
      --local shape and fixture because you only need them once for creation.
      local shape
      local fixture
      if e.shape.form == "rect" then
        shape = love.physics.newRectangleShape(e.shape.size.x-2, e.shape.size.y-2)
      elseif e.shape.form == "circ" then
        --Divide size in half since this take a radius
        shape = love.physics.newCircleShape(e.shape.size.x/2 - 1)
      elseif e.shape.form == "ast" then
       shape = love.physics.newCircleShape(e.shape.size.x/2 - 15)
      end
      
      fixture  = love.physics.newFixture(e.physics.body, shape, e.physics.density) --attach shape to body
      
      fixture:setCategory(e.physics.category)
      fixture:setUserData(e)
      if e.physics.mask then
       fixture:setMask(e.physics.mask)
      end
      
      --Prevents outside forces from rotating the player's ship
      if e.physics.category == 2 then
        e.physics.body:setFixedRotation(true)
      end
      
      
      if e.physics.startAngle then
        e.physics.body:setAngle(e.physics.startAngle)
      end
      
      
      if e.physics.startXVel then
        e.physics.body:applyLinearImpulse(e.physics.startXVel, 0)
      end
      if e.physics.startYVel then
        e.physics.body:applyLinearImpulse(0, e.physics.startYVel)
      end
      
    else --update  positions and such
      e.position.x = e.physics.body:getX()
      e.position.y = e.physics.body:getY()
      
      --Remove if behind player
      local cx,cy = camera:pos()
      if e.physics.body:getX() < cx - 3500 then
        e.physics.body:destroy()
        EntitySystem.delete(e)
      
    end 
  end
  
  end
 
  --step
  world:update(dt)
end)
  